<?php 
include "../../Lib/DBMySql.inc";
include "../../Lib/Common.php";
include "../../Entities/bannersObj.php";
include "../../DAL/bannersDAL.php";
include "../../Entities/bannershistObj.php";
include "../../DAL/bannershistDAL.php";
include "../../Entities/webpagesObj.php";
include "../../DAL/webpagesDAL.php";
include "../../Entities/pagepositionsObj.php";
include "../../DAL/pagepositionsDAL.php";
include "../../Entities/bannerpositionsObj.php";
include "../../DAL/bannerpositionsDAL.php";
include "../../Entities/bannerpositionshistObj.php";
include "../../DAL/bannerpositionshistDAL.php";
include "../../Lib/Content.php";
include "../../Lib/ExtraFuncs.php";
include "../../Lib/Session.php";

// If user not is administrator/partner manager then he/she can't user this page
if ($userSess->userroleID>1)
{
	header("Location: ../report/list.php");
	exit;	   
}
try
{
	$mainDB = NewDB(DATABASE_HOST, DATABASE_NAME , DATABASE_USER, DATABASE_PASSWORD);
	if (!isset($txtID) || $txtID=="")	$title		= "Add New Banner";
	else	$title		= "Edit Banner Information";
	$pageBack = "list.php";
	$frmName = "frmMain";
	$pageError	= "";
	
	$uploadPath = WS_ROOT."uploadfiles/banner/";
	
	if (isset($act) && $act=="DELETE" && isset($deletedFile) && $deletedFile != "") {
		unlink($uploadPath.$deletedFile);
		$banner = bannersDAL::Load($mainDB, $txtID, $pageError);
		if ($banner->image==$deletedFile)
			$banner->image = "";
		else $image = $banner->image;
		if ($banner->popImage==$deletedFile)
			$banner->popImage = "";	
		else $popImage = $banner->popImage;	
		bannersDAL::Update($mainDB, $banner, $pageError);
	}

	if (isset($act) && ($act=="ADD" ||$act=="EDIT")) {
		if ($act=="EDIT") $editFilter = "AND id<>$txtID";
		$exist = bannersDAL::IsExist($mainDB,  bannersObj::nameFieldName()."='".mysql_escape_string($name)."' $editFilter");
		
		if ($exist) 
			$pageError = "Name is duplicated.";
		else
		{
			$fimage = UploadFile("image", $uploadPath);
			$fpopImage = UploadFile("popImage", $uploadPath);
			if ($act=="ADD") {
				$banners = new bannersObj();
				bannersDAL::Pop($banners);
				$banners->startDate = VNSupplierDateToMysql($banners->startDate);
				$banners->endDate = VNSupplierDateToMysql($banners->endDate);
				if ($fimage!="")
					$banners->image = $fimage;
				if ($fpopImage!="")
					$banners->popImage = $fpopImage;
				if (!bannersDAL::Insert($mainDB, $banners, $error)) 
					$pageError = "Invalid inserting. ($error).";
				else  {
					if (isset($chkPagePositions) && is_array($chkPagePositions))
					{
						for ($i=0; $i<count($chkPagePositions); $i++)
						{
							$bannerPosition = new bannerpositionsObj();
							$bannerPosition->bannerID = $banners->id;
							$bannerPosition->pagePositionID	= $chkPagePositions[$i];
							
							bannerpositionsDAL::Insert($mainDB, $bannerPosition, $error);
						}
					}
					$exit = true;
				}
			} else if ($act=="EDIT") {
				$banners = new bannersObj();
				$banners = bannersDAL::Load($mainDB, $txtID, $pageError);
				$imagePath = $banners->image; 
				$popImagePath = $banners->popImage; 
				bannersDAL::Pop($banners);
				$banners->startDate = VNSupplierDateToMysql($banners->startDate);
				$banners->endDate = VNSupplierDateToMysql($banners->endDate);
				$banners->id = $txtID;
				if ($fimage!="")
					$banners->image = $fimage;
				else
					$banners->image = $imagePath;
				if ($fpopImage!="")
					$banners->popImage = $fpopImage;
				else
					$banners->popImage = $popImagePath;	
				if (!bannersDAL::Update($mainDB, $banners, $error)) 
					$pageError = "Invalid updating. ($error).";
				else {
					//echo 123;
					bannerpositionsDAL::Pure($mainDB, "bannerID=".$banners->id, $error);
					if (isset($chkPagePositions) && is_array($chkPagePositions))
					{
						for ($i=0; $i<count($chkPagePositions); $i++)
						{
							$bannerPosition = new bannerpositionsObj();
							$bannerPosition->bannerID = $banners->id;
							$bannerPosition->pagePositionID	= $chkPagePositions[$i];
							
							bannerpositionsDAL::Insert($mainDB, $bannerPosition, $error);
						}
					}
					$exit = true;
				}
			}
		}
	}
	if (isset($txtID) && $txtID!="" && !isset($name)) {
		$banners = bannersDAL::Load($mainDB, $txtID, $pageError);
		if ($pageError=="" && $banners!=null) {
			bannersDAL::Push($banners);
		}
	} else {
		$deleteFlag	= 0;
		$popWidth 	= 0;
		$popHeight	= 0;
		$delayPeriod= 0;
	}
	$pagepositions = pagepositionsDAL::GetList($mainDB, "", "webpageID, name", "", $pageError);
	$script = "var webpageIDs = Array(); var pagePositionIDs = Array(); var pagePositionNames = Array();";

	for ($i=0; $i<count($pagepositions); $i++)
	{
		$script .= "webpageIDs[$i] = ".$pagepositions[$i]->webpageID.";";
		$script .= "pagePositionIDs[$i] = ".$pagepositions[$i]->id.";";
	}
} 
catch(Exception $ex)
{ $pageError = $ex.message;}

if ($exit)
{
	$bannerHist = new bannershistObj();
	$bannerHist->histID = $banners->id;
	$bannerHist->name = $banners->name;
	$bannerHist->description = $banners->description;
	$bannerHist->image = $banners->image;
	$bannerHist->popImage = $banners->popImage;
	$bannerHist->popWidth = $banners->popWidth;
	$bannerHist->popHeight = $banners->popHeight;
	$bannerHist->linkUrl = $banners->linkUrl;
	$bannerHist->urlForView = $banners->urlForView;
	$bannerHist->urlForClick = $banners->urlForClick;
	$bannerHist->webpageID = $banners->webpageID;
	$bannerHist->delayPeriod = $banners->delayPeriod;
	$bannerHist->startDate = $banners->startDate;
	$bannerHist->endDate = $banners->endDate;
	$bannerHist->price = $banners->price;
	$bannerHist->deleteFlag = $banners->deleteFlag;
	$bannerHist->issueDate = date("Y-m-d H:i:s");
	$bannerHist->issueBy = $userSess->id;

	bannershistDAL::Insert($mainDB, $bannerHist, $error);
	
	for ($i=0; $i<count($chkPagePositions); $i++)
	{
		$bannerPosition = new bannerpositionshistObj();
		$bannerPosition->bannerID = $banners->id;
		$bannerPosition->pagePositionID	= $chkPagePositions[$i];
		$bannerPosition->histID = $bannerHist->id;
		
		bannerpositionshistDAL::Insert($mainDB, $bannerPosition, $error);
	}
	
}

include "../header.php";
?>
<form name=<?php  echo $frmName;?> method=post action="<?php  echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<input type=hidden name=page value="<?php echo $page;?>">
<input type=hidden name=act value="<?php  if (!isset($txtID) || $txtID=="") echo "ADD"; else echo "EDIT";?>">
<input type=hidden name=txtID value="<?php  echo $txtID;?>">
<input type=hidden name=SortField value="<?php echo $SortField;?>">
<input type=hidden name=SortType value="<?php echo $SortType;?>">
<input type=hidden name=deleteFlag value="<?php echo $deleteFlag;?>">
<input type=hidden name="deletedFile">

<script>
<?php  echo $script;?>
<?php  if (isset($exit)) echo "document.$frmName.action = '$pageBack'; document.$frmName.submit();";?>
function ValidSubmit() {
	frm = document.<?php  echo $frmName;?>;
	
	if (!_CF_hasValue(frm.name, "TEXT")) {
		alert("Please enter name");
		frm.name.focus();
		return false;
	}
	<?php  if (!isset($txtID) || $txtID=="") {?>
	if (frm.image.value=="") {
		alert("Please select banner");
		frm.image.focus();
		return false;
	}
	<? }?>
	
	if (_CF_hasValue(frm.popWidth, "TEXT") && !_CF_checkinteger(frm.popWidth.value)) {
		alert("Invalid popup width, you must input a integer number data.");
		frm.popWidth.focus();
		return false;
	} else if (!_CF_checkinteger(frm.popWidth.value)) frm.popWidth.value = 0;
	
	if (_CF_hasValue(frm.popHeight, "TEXT") && !_CF_checkinteger(frm.popHeight.value)) {
		alert("Invalid popup height, you must input a integer number data.");
		frm.popHeight.focus();
		return false;
	} else if (!_CF_checkinteger(frm.popHeight.value))  frm.popHeight.value = 0;
	if (frm.webpageID.value=='' || frm.webpageID.value=='0') {
		alert("Please select web page");
		frm.webpageID.focus();
		return false;
	}

	if (!_CF_hasValue(frm.delayPeriod, "TEXT")) {
		alert("Please enter period");
		frm.delayPeriod.focus();
		return false;
	}
	if (_CF_hasValue(frm.delayPeriod, "TEXT") && !_CF_checkinteger(frm.delayPeriod.value)) {
		alert("Invalid popup period, you must input a integer number data.");
		frm.delayPeriod.focus();
		return false;
	} else if (!_CF_checkinteger(frm.delayPeriod.value))  frm.delayPeriod.value = 0;

	// Check number field
	if (!_CF_hasValue(frm.price, "TEXT")) {
		frm.price = '0.00';
	}
	if (_CF_hasValue(frm.price, "TEXT") && !_CF_checknumber(frm.price.value)) {
		alert("Invalid price, you must input a numeric data.");
		frm.price.focus();
		return false;
	}
	
	if (!_CF_hasValue(frm.startDate, "TEXT")) {
		alert("Please enter start date");
		frm.startDate.focus();
		return false;
	}

	if (!_CF_hasValue(frm.endDate, "TEXT")) {
		alert("Please enter end date");
		frm.endDate.focus();
		return false;
	}
	
	return true;		
}
function Delete(file) {
	frm = document.<?php  echo $frmName;?>;
	if (confirm("Do you want to delete the image?"))
	{
		frm.act.value = "DELETE";
		frm.deletedFile.value = file;
		frm.submit();
	}
}
function changeWebpage() {
	frm = document.<?php  echo $frmName;?>;

	for (i=0; i<pagePositionIDs.length; i++) {
		
		frmlen=frm.length;
		for (ielement=0;ielement<frmlen;ielement++) {
			ElenameName=frm.elements[ielement].name;
			if (ElenameName == "chkPagePositions[]") {
				frm.elements[ielement].checked = false;
			}
		}
		
		chk = document.getElementById("chk" + pagePositionIDs[i]);
		if (chk!=null)
		{
			if (webpageIDs[i] == frm.webpageID.value) 
				chk.style.display = "table-row";
			else	
				chk.style.display = "none";
		}

	}
}
</script>
<table width="97%" border="0" cellspacing="0" cellpadding="0" align="center">
	<tr valign=middle> 
		<td class="titleText" colspan=3 height=25><?php  echo $title;?></td>
	</tr>
	<tr> 
		<td align="center" valign="top" colspan=3>
			<table width="100%" border=1 cellspacing="1" class="formBackGround">
				<tr>
					<td>
						<TABLE border=0 class="gridBody" cellPadding=0 cellspacing="0" width="100%">
							<tr class="gridHeader">
								<td colspan=4 height=20 class='errortext'>&nbsp;<? echo $pageError;?>&nbsp;</td>
							</TR>
							<tr height=5>
								<td colspan=4 height=5></td>
							</TR>
							
							<tr class="gridBody">
								<td width="10" nowrap>&nbsp;</td>
								<td width="20%" nowrap>Name<font color="#cc0000">*</font>:&nbsp;</td>
								<td width="10" nowrap>&nbsp;</td>
								<td width="80%" nowrap><input type=text name="name" value="<?php  echo $name;?>" size="80" maxlength="255" class="inputText">&nbsp;</td>
							</TR>

							<tr class="gridBody">
								<td width="10" nowrap>&nbsp;</td>
								<td width="20%" nowrap>Description<font color="#cc0000"></font>:&nbsp;</td>
								<td width="10" nowrap>&nbsp;</td>
								<td width="80%" nowrap><input type=text name="description" value="<?php  echo $description;?>" size="80" maxlength="255" class="inputText">&nbsp;</td>
							</TR>

							<tr class="gridBody">
								<td width="10" nowrap>&nbsp;</td>
								<td width="20%" nowrap>Banner<font color="#cc0000">*</font>:&nbsp;</td>
								<td width="10" nowrap>&nbsp;</td>
								<td width="80%" nowrap><input type=file class='inputText' name='image' size='52'>&nbsp;
                                    <?php
									if ($image!="")
									{
										list($lpicture_x, $lpicture_y) = @GetImageSize($uploadPath.$image); 
										$lpicture_x += 25;
										$lpicture_y += 35;
										echo "<a href=\"#\" title=\"View Image\" onClick=\"viewpicture('".URL_SITE."uploadfiles/banner/$image', $lpicture_x, $lpicture_y); return false;\">View Image</a> | ";
										echo "<a href='#' onClick=\"Delete('$image');\">Delete</a>&nbsp;";
									}
									?>&nbsp;</td>
							</TR>

							<tr class="gridBody">
								<td width="10" nowrap>&nbsp;</td>
								<td width="20%" nowrap>Popup banner<font color="#cc0000"></font>:&nbsp;</td>
								<td width="10" nowrap>&nbsp;</td>
								<td width="80%" nowrap><input type=file class='inputText' name='popImage' size='52'>&nbsp;
                                    <?php
									if ($popImage!="")
									{
										list($lpicture_x, $lpicture_y) = @GetImageSize($uploadPath.$popImage); 
										$lpicture_x += 25;
										$lpicture_y += 35;
										echo "<a href=\"#\" title=\"View Image\" onClick=\"viewpicture('".URL_SITE."uploadfiles/banner/$popImage', $lpicture_x, $lpicture_y); return false;\">View Image</a> | ";
										echo "<a href='#' onClick=\"Delete('$popImage');\">Delete</a>&nbsp;";
									}
									?>&nbsp;</td>
							</TR>

							<tr class="gridBody">
								<td width="10" nowrap>&nbsp;</td>
								<td width="20%" nowrap>Popup width<font color="#cc0000"></font>:&nbsp;</td>
								<td width="10" nowrap>&nbsp;</td>
								<td width="80%" nowrap><input type=text name="popWidth" value="<?php  echo $popWidth;?>" size="10" maxlength="5" class="inputText">&nbsp;</td>
							</TR>

							<tr class="gridBody">
								<td width="10" nowrap>&nbsp;</td>
								<td width="20%" nowrap>Popup height<font color="#cc0000"></font>:&nbsp;</td>
								<td width="10" nowrap>&nbsp;</td>
								<td width="80%" nowrap><input type=text name="popHeight" value="<?php  echo $popHeight;?>" size="10" maxlength="5" class="inputText">&nbsp;</td>
							</TR>

							<tr class="gridBody">
								<td width="10" nowrap>&nbsp;</td>
								<td width="20%" nowrap>Link to URL<font color="#cc0000"></font>:&nbsp;</td>
								<td width="10" nowrap>&nbsp;</td>
								<td width="80%" nowrap><input type=text name="linkUrl" value="<?php  echo $linkUrl;?>" size="80" maxlength="255" class="inputText">&nbsp;</td>
							</TR>

							<tr class="gridBody">
								<td width="10" nowrap>&nbsp;</td>
								<td width="20%" nowrap>Link URL for view<font color="#cc0000"></font>:&nbsp;</td>
								<td width="10" nowrap>&nbsp;</td>
								<td width="80%" nowrap><input type=text name="urlForView" value="<?php  echo $urlForView;?>" size="80" maxlength="255" class="inputText">&nbsp;</td>
							</TR>

							<tr class="gridBody">
								<td width="10" nowrap>&nbsp;</td>
								<td width="20%" nowrap>Link URL for click<font color="#cc0000"></font>:&nbsp;</td>
								<td width="10" nowrap>&nbsp;</td>
								<td width="80%" nowrap><input type=text name="urlForClick" value="<?php  echo $urlForClick;?>" size="80" maxlength="255" class="inputText">&nbsp;</td>
							</TR>

							<tr class="gridBody" height=18>
								<td width="10" nowrap>&nbsp;</td>
								<td width="20%" nowrap>Web page<font color="#cc0000">*</font>:&nbsp;</td>
								<td width="10" nowrap>&nbsp;</td>
								<td width="80%" nowrap><?php  echo GetComboBox($mainDB, webpagesObj::TableName(), "", "", "webpageID", "id", "name", "Select one", "", ${"webpageID"}, "class='inputText' onChange='changeWebpage();'");?>&nbsp;</td>
							</TR>

							<tr class="gridBody" height=18>
								<td width="10" nowrap>&nbsp;</td>
								<td width="20%" nowrap>Page positions<font color="#cc0000">*</font>:&nbsp;</td>
								<td width="10" nowrap>&nbsp;</td>
								<td width="80%" nowrap>
                                	<table border=0>
                                    	<?php
										for ($i=0; $i<count($pagepositions); $i++)
										{
											$display = "none";
											if ($pagepositions[$i]->webpageID == ${"webpageID"})
												$display = "table-row";
											?>
	                                    	<tr id="chk<?=$pagepositions[$i]->id?>" style="display:<?=$display?>">
                                            <?	
											for ($j=$i; $j<count($pagepositions) && $j<$i+3; $j++)
											{
												if ($pagepositions[$i]->webpageID!=$pagepositions[$j]->webpageID) {
													$k = $j;
													while ($k<$i+3) { echo "<td>&nbsp;</td>"; $k++;}
													break;
												}
												$chk = bannerpositionsDAL::IsExist($mainDB, bannerpositionsObj::bannerIDFieldName()."=".$txtID." AND ".bannerpositionsObj::pagePositionIDFieldName()."=".$pagepositions[$j]->id);
												if ($chk) $chk = " CHECKED";
												else $chk = "";
												?>
                                                	<td width="33%" nowrap="nowrap"><input type=checkbox name="chkPagePositions[]" value="<?=$pagepositions[$j]->id?>"<?=$chk?>> <?=$pagepositions[$j]->name?></td>
                                                <?
											}
											$i = $j-1;
											if ($i==count($pagepositions)-1)
											{
												$k = ($i+2)%3;
												while ($k<=3) { echo "<td>&nbsp;</td>"; $k++;}
											}
										?>
                                        	</tr>

                                        <?php
                                        }?>    
                                    </table>
                                </td>
							</TR>

							<tr class="gridBody">
								<td width="10" nowrap>&nbsp;</td>
								<td width="20%" nowrap>Period<font color="#cc0000">*</font>:&nbsp;</td>
								<td width="10" nowrap>&nbsp;</td>
								<td width="80%" nowrap><input type=text name="delayPeriod" value="<?php  echo $delayPeriod;?>" size="15" maxlength="5" class="inputText">&nbsp;</td>
							</TR>

							<tr class="gridBody">
								<td width="10" nowrap>&nbsp;</td>
								<td width="20%" nowrap>Price<font color="#cc0000">*</font>:&nbsp;</td>
								<td width="10" nowrap>&nbsp;</td>
								<td width="80%" nowrap><input type=text name="price" value="<?php  echo $price;?>" size="15" maxlength="5" class="inputText">&nbsp;</td>
							</TR>

							<tr class="gridBody">
								<td width="10" nowrap>&nbsp;</td>
								<td width="20%" nowrap>Start date<font color="#cc0000">*</font>:&nbsp;</td>
								<td width="10" nowrap>&nbsp;</td>
								<td width="80%" nowrap><input id="startDate" type=text name="startDate" type="text" class="inputText" value="<?php  echo  VNSupplierShowDate($startDate, true);?>" size="20"><a href="javascript:NewCal('startDate','ddmmmyyyy',true,12)"><img src="<?php  echo URL_SITE;?>images/cal.gif" width="16" height="16" border="0" alt="Pick a date"></a>&nbsp;</td>
							</TR>

							<tr class="gridBody">
								<td width="10" nowrap>&nbsp;</td>
								<td width="20%" nowrap>End date<font color="#cc0000">*</font>:&nbsp;</td>
								<td width="10" nowrap>&nbsp;</td>
								<td width="80%" nowrap><input id="endDate" type=text name="endDate" type="text" class="inputText" value="<?php  echo VNSupplierShowDate($endDate, true);?>" size="20"><a href="javascript:NewCal('endDate','ddmmmyyyy',true,12)"><img src="<?php  echo URL_SITE;?>images/cal.gif" width="16" height="16" border="0" alt="Pick a date"></a>&nbsp;</td>
							</TR>
<input type=hidden name='deleteFlag' value='<? echo $deleteFlag;?>'>
							<?php  
								if (!isset($txtID) || $txtID=="")
									include "../../Lib/bottomNewAct.php";
								else 
									include "../../Lib/bottomUpdateAct.php";
							?>
							<tr class="gridFooter" height=20>
								<td colspan=4></td>
							</TR>
						</TABLE>
					</td>
				</tr>
			</TABLE>
		</td>
	</tr>
</table>
</form>
<?php 
include "../footer.php";
?>